package com.imonsoft.common.util.upload;

import java.io.IOException;
import java.io.InputStream;
import java.util.UUID;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;
import org.springframework.util.Assert;
import org.springframework.web.multipart.MultipartFile;

import com.imonsoft.common.util.ContextUtil;
import com.imonsoft.common.util.DateUtil;
import com.imonsoft.common.util.FileUtil;
import com.imonsoft.common.util.MD5Util;

/**
 * 
 * @author LiQianHui
 * @date 2011-8-29
 * @version 2011
 */
public abstract class UpFileUtil {

	protected final Log logger = LogFactory.getLog(getClass());

	public static final String USERFILE = "/UserFiles/";

	/**
	 * @param mFile
	 * @param hbPhoto
	 * @return
	 */
	public static String upFile(MultipartFile mFile) {
		Assert.notNull(mFile, "上传的文件不能为空");
		ContextUtil.setFlashMessage("成功！");
		String webPath = FileUtil.getRealPath();
		String fileName = mFile.getOriginalFilename();
		String suffix = fileName.substring(fileName.lastIndexOf("."));// 后缀名

		String saveFileName = MD5Util.encode(UUID.randomUUID().toString());// 唯一名称
		fileName = saveFileName + suffix;

		String subPath = DateUtil.getNowDate("yyyy/MM/dd");
		String savepath = webPath + USERFILE + subPath;

		InputStream is = null;
		try {
			// 获得输入流
			is = mFile.getInputStream();
			FileUtil.save(is, savepath, fileName);
		} catch (IOException e) {
			e.printStackTrace();
			ContextUtil.setFlashMessage("错误:" + e.getMessage());
		} finally {
			if (is != null) {
				try {
					is.close();
				} catch (IOException e) {
					e.printStackTrace();
					ContextUtil.setFlashMessage("错误:" + e.getMessage());
				}
			}
		}
		String returnPath = savepath.replace(webPath, "") + fileName;
		return returnPath;
	}
}
